/**
 *
 * @authors liwb (lwbhtml@gmail.com)
 * @date    2018/6/5 上午10:43
 * @description 请求封装
 */
import axios, { AxiosRequestConfig } from 'axios';
import { MessageBox } from 'element-ui'
import router from '../router'
let obj = {
  isOpenMessage: true //是否开启提示告警弹窗
}
var getToken = function (): string {
  var storage = window.localStorage;
  var userinfs: string | null = storage.getItem("userinf");
  if (userinfs) {
    var jsonObj = JSON.parse(userinfs || "");
    return jsonObj.token
  } else {
    return ''
  }
}
var getLoginSign = function (): string {
  var storage = window.localStorage;
  var userinfs: string | null = storage.getItem("userinf");
  if (userinfs) {
    var jsonObj = JSON.parse(userinfs || "");
    return jsonObj.loginSign
  } else {
    return ''
  }
}

// 添加一个请求拦截器 （于transformRequest之前处理）
axios.interceptors.request.use((config) => {
  // Do something before request is sent
  if (!(getToken() == "")) {
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['Authorization'] = 'Bearer' + ' ' + getToken();
    config.headers['LoginSign'] = getLoginSign();
    // config.headers['x-client-token-user'] ='%7B%20%20%20%20%22orgType%22%3A%20%22CITY%22%2C%20%20%20%20%22orgValue%22%3A%20%228a1ea5c64bdebad1014bdebc55c80162%22%2C%20%20%20%20%22orgCityValue%22%3A%20%228a1ea5c64bdebad1014bdebc55c80162%22%2C%20%20%20%20%22bzlx%22%3A%20null%2C%20%20%20%20%22userName%22%3A%20%22%E5%9B%BD%E7%BD%91%E6%B5%8E%E5%8D%97%E4%BE%9B%E7%94%B5%E5%85%AC%E5%8F%B8%22%7D'
  }
  return config;
}, (error) => {
  // 当出现请求错误是做一些处理
  return Promise.reject(error);
});

// 添加一个返回拦截器 （于transformResponse之后处理）
// 返回的数据类型默认是json，若是其他类型（text）就会出现问题，因此用try,catch捕获异常
axios.interceptors.response.use((response) => {
  return checkStatus(response);
}, (error) => {
  // 对返回的错误进行一些处理
  // 超时处理
  if (error.code === 'ECONNABORTED') {
    return;
  }
  return Promise.reject(checkStatus(error));
});

function checkStatus(response: any) {
  // 如果http状态码正常，则直接返回数据
  if (response) {
    const status = response.status || -1000;
    const data = response.data || {}
    let code = data.code
    if (code === 2001) {
      // 无效token
      if (obj.isOpenMessage) {

        MessageBox.confirm('会话超时请重新登录！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            obj.isOpenMessage = true
            console.log(router);
            router.push({
              path: "/login",
            });
          })
          .catch(() => {
            obj.isOpenMessage = true
           })
        obj.isOpenMessage = false
      }
    } else if (code === 2003) {
      // token过期
      if (obj.isOpenMessage) {
        MessageBox.confirm('会话超时请重新登录！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(() => {
            obj.isOpenMessage = true
            console.log(router);
            router.push({
              path: "/login",
            });
          })
          .catch(() => {
            obj.isOpenMessage = true
           })
        obj.isOpenMessage = false
      }
    } else if ((status >= 200 && status < 300) || status === 304) {
      // 如果不需要除了data之外的数据，可以直接 return response.data
      return response.data;
    } else {
      let errorInfo = '';
      switch (status) {
        case 1:
          errorInfo = '1: 系统繁忙,请稍候再试';
          break;
        case 500:
          errorInfo = '500: 错误请求';
          break;
        case 4098:
          errorInfo = '4098: 网关超时';
          break;
        case 4356:
          errorInfo = '4356: 服务未找到';
          break;
        case 4416:
          errorInfo = '4416: 网关异常';
          break;
        case 8192:
          errorInfo = '8192: 无效token';
          break;
        case 8200:
          errorInfo = '8200: 上传文件大小超过限制';
          break;
        case 12288:
          errorInfo = '12288：唯一键冲突';
          break;
        case 12352:
          errorInfo = '12352：用户未找到！';
          break;
        case 12416:
          errorInfo = '12416：角色未找到！';
          break;
        case -1:
          errorInfo = '-1: 系统异常';
          break;
        default:
          errorInfo = `连接错误${status}`;
      }
      return {
        status,
        msg: errorInfo
      };
    }
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  };
}

export default function request(url: string, {
  method = 'get',
  timeout = 60000,
  prefix = '',
  data = {},
  file = false,
  headers = {},
  dataType = 'json',
  postparams = false,
  fromdata = false
}) {
  const baseURL = (window as any).VUE_APP_BASEURL;

  var HEADER = {}
  if (method === 'get') {
    HEADER = {
      'Accept': 'application/json',
      'Content-Type': 'application/json; charset=UTF-8'
    }
  }
  if (fromdata === true) {
    HEADER = {
      'Content-Type': 'application/x-www-form-urlencoded;'
    }
  }
  headers = Object.assign(HEADER, headers);

  const defaultConfig = {
    baseURL,
    url,
    method,
    params: data,
    data,
    timeout,
    headers,
    responseType: dataType
  };

  if (method === 'get') {
    delete defaultConfig.data;
  } else {
    if (method === 'post' && postparams === false) {
      delete defaultConfig.params;
    }
    if (method === 'put' && postparams === true) {
      delete defaultConfig.data;
    }
    if (method === 'delete' && postparams === true) {
      delete defaultConfig.data;
    }
  }
  return axios(defaultConfig as AxiosRequestConfig);
}
